package top.guagua.web.controller;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import top.guagua.api.result.VisitorResult;
import top.guagua.api.srv.VisitService;
import top.guagua.core.util.IpUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
public class VisitController {

	private static final Logger logger = LoggerFactory.getLogger(VisitController.class);

	@Autowired
	private VisitService visitService;

//	@RequestMapping(value = "/*")
//	public BaseResponseList<VisitorResult> hello(HttpServletRequest request, HttpServletResponse response){
//		BaseResponseList<VisitorResult> resp = new BaseResponseList<>();
//		VisitorResult visitorResult = new VisitorResult();
//		visitorResult.setIp(IpUtil.getIp(request));
//		visitorResult.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//		visitorResult.setUri(request.getRequestURI());
//		List<VisitorResult> results = visitService.saveVisitor(visitorResult);
//		resp.setResult(results);
//		return resp;
//	}

	@RequestMapping(value = "/*")
	public String hello(HttpServletRequest request, HttpServletResponse response, ModelMap map){
		VisitorResult visitorResult = new VisitorResult();
		visitorResult.setIp(IpUtil.getIp(request));
		visitorResult.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		visitorResult.setUri(request.getRequestURI());
		logger.info("New Visitor:{}", JSON.toJSONString(visitorResult));
		List<VisitorResult> results = visitService.saveVisitor(visitorResult);
		logger.info("GET_Latest_Visitors:{}", JSON.toJSONString(visitorResult));
		map.put("visitors",results);
		return "index";
	}
}
